const Router = require('koa-router');
const path = require('path');
const comm = require('./common');
module.exports =function (fields, table, page_type) {
    let router = new Router();
    const page_types = {
        banner: 'banner管理',
        catalog: 'catalog管理',
        article: 'article管理'
    };
    router.get('/', async ctx =>{
        let {HTTP_ROOT} = ctx.config;
        let username = ctx.session['admin'];
        let datas = await ctx.db.query(`SELECT * FROM ${table}`);
        fields.forEach(async item =>{
           if(item.type== 'select'){
               item.select = await ctx.db.query(item.from)
           }
        });
        await ctx.render('admin/table',{
            datas,
            username,
            page_type,
            page_types,
            HTTP_ROOT,
            fields
        });
    });
    router.post('/',async ctx=>{
        let {HTTP_ROOT} = ctx.config;
        let vals = [];
        let keys = [];
        fields.forEach(item =>{
            const {name, type} = item;
            keys.push(name);
            if(type == 'file'){
                vals.push(path.basename(ctx.request.fields[name][0].path))
            }else if(type == 'date') {
                vals.push(Math.floor(new Date(ctx.request.fields[name]).getTime()/1000))
            }else{
                vals.push(ctx.request.fields[name])
            }
        });
        await ctx.db.query(`INSERT INTO ${table}(${keys.join(',')}) VALUES(${keys.map(key=>'?').join(',')})`, vals);
        ctx.redirect(`${HTTP_ROOT}/admin/${page_type}`);
    });
    router.get('/delete/:id/', async ctx=>{
        let {HTTP_ROOT,UPLOAD_DIR} = ctx.config;
        let {id} = ctx.params;
        let data = await ctx.db.query(`SELECT * FROM ${table} WHERE ID=?`, [id]);
        ctx.assert(data.length,400, 'no data');
        let row = data[0];
        fields.forEach(async ({name,type})=>{
            if(type=='file'){
                await comm.unlink(path.resolve(UPLOAD_DIR, row[name]));
            }
        });
        await ctx.db.query(`DELETE FROM ${table} WHERE ID=?`, [id]);
        ctx.redirect(`${HTTP_ROOT}/admin/${page_type}`);
    });
    router.post('/modify/:id',async ctx =>{
        let post = ctx.request.fields;
        let {id} = ctx.params;
        let {HTTP_ROOT,UPLOAD_DIR} = ctx.config;
        // 获取数据库的src
        let rows = await ctx.db.query(`SELECT * FROM ${table} WHERE ID =?`, [id]);
        ctx.assert(rows.length,400,'no data');
        let paths = {};
        fields.forEach(({name,type})=>{
            if(type=='file'){
                path[name] = rows[0][name]; //循环保存所以的值
            }
        });
        let keys = [];
        let vals = [];
        let src_change = {};
        fields.forEach(({name,type})=>{
            if(type=='file'){
                if(post[name] && post[name].length && post[name][0].size){
                    src_change[name] = true;
                    keys.push(name);
                    vals.push(path.basename(post[name][0].path));
                }
            } else if(type == 'date') {
                keys.push(name);
                vals.push(Math.floor(new Date(post[name]).getTime()/1000))
            }else{
                keys.push(name);
                vals.push(post[name]);
            }
        });
        await ctx.db.query(`UPDATE ${table} SET ${
            keys.map(key => (`${key}=?`)).join(',')
            } WHERE ID=?`, [...vals, id]);
        fields.forEach(async ({name,type})=>{
            if(type == 'file' && src_change[name]){
                await comm.unlink(path.resolve(UPLOAD_DIR, paths[name]))
            }
        });
        ctx.redirect(`${HTTP_ROOT}/admin/${page_type}`);
    });
//修改前台调用 api接口
    router.get(`/get/:id`,async ctx=>{
        let {id}= ctx.params;
        let rows = await ctx.db.query(`SELECT * FROM ${table} WHERE ID =?`, [id]);
        if(rows.lenght ==0){
            ctx.body={err:1,msg: 'no data'}
        }else{
            ctx.body = {err:0, msg: 'success', data: rows[0]}
        }
    });
    return router.routes();
}